<template>
  <div class="app-container">
    <div class="search-container">
      <!-- 头部查询表单 -->
      <el-form ref="QueryFormRef" :inline="true" :model="params">
        <el-form-item>
          <el-button type="primary" @click="resetQuery">
            <el-icon>
              <refresh/>
            </el-icon>
            查询全部
          </el-button>
          <el-button :disabled="selectionIds.length === 0" type="danger" @click="handleBatchDelete">
            <el-icon>
              <delete/>
            </el-icon>
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table v-loading="orderTableLoading" :data="orderDataList"
                :span-method="objectSpanMethod" border highlight-current-row
                @selection-change="handleSelectionChange" @row-click="handleRowClick"
      >
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" label="用户id" prop="userId" width="175"/>
        <el-table-column align="center" label="订单id" prop="id" width="175"/>
        <el-table-column align="center" label="报价" prop="quotation" width="150"/>
        <el-table-column align="center" label="付款" prop="payment" width="150"/>
        <el-table-column align="center" label="交易金额" prop="totalAmount" width="150"/>
        <el-table-column align="center" label="状态" width="125">
          <template #default="scope">
            <el-tag :type="status[scope.row.status-1].type" style="margin-bottom: 0.5em">
              {{ status[scope.row.status - 1].value }}
            </el-tag>
            <el-tag v-if="scope.row.status !== 7" :type="cancel[scope.row.cancel].type">
              {{ cancel[scope.row.cancel].value }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" min-width="300" prop="remarks"/>
        <el-table-column :formatter="formatter" align="center" label="创建时间" prop="ctime" width="150"/>
        <el-table-column :formatter="formatter" align="center" label="完成时间" prop="dtime" width="150"/>
        <el-table-column :formatter="formatter" align="center" label="买家付款时间" prop="gmtPayment" width="150"/>
        <el-table-column align="center" label="买家支付宝唯一id" prop="buyerId" width="150"/>
        <el-table-column align="center" label="买家交易凭证号" prop="tradeNo" width="150"/>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link size="small" type="primary" @click.stop="openOrderStatusDialog(scope.row)">
              <el-icon>
                <edit/>
              </el-icon>
              订单状态
            </el-button>
            <el-button link size="small" type="primary" @click.stop="handleDelete(scope.row)">
              <el-icon>
                <delete/>
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:page="params.page"
          v-model:size="params.size"
          v-model:total="total"
          @pagination="handleQuery"
      />
    </el-card>
    <!-- 修改状态弹窗 -->
    <el-dialog
        v-model="orderStatusDialog.visible" :title="orderStatusDialog.title" align-center
        width="65%" @close="closeOrderStatusDialog"
    >
      <el-steps :active="orderStatusDialog.status" align-center finish-status="success"
                process-status="process" style="max-width: 600px">
        <el-step v-for="item in status" :key="item.key" :title="item.value"/>
      </el-steps>
      <el-result v-if="orderStatusDialog.cancel !== 1&&orderStatusDialog.cancel !== 2"
                 :icon="status[orderStatusDialog.status-1].type"
                 :title="status[orderStatusDialog.status-1].value"
      >
        <template v-if="orderStatusDialog.status === 2" #extra>
          <div style="display: flex; flex-direction: column; align-items: center;">
            <el-input-number v-model="orderStatusDialog.quotation" :min="0" placeholder="允许小数"
                             style="min-width: 150px"/>
            <el-button style="margin-top: 1rem" type="success" @click="handleOrderStatusStep(3)">确定报价</el-button>
          </div>
        </template>
        <template v-if="orderStatusDialog.status === 4" #extra>
          <el-button type="primary" @click="handleOrderStatusStep(5)">开始打印</el-button>
        </template>
        <template v-if="orderStatusDialog.status === 5" #extra>
          <el-button type="primary" @click="handleOrderStatusStep(6)">打印完成</el-button>
        </template>
      </el-result>
      <el-result v-else
                 :icon="cancel[orderStatusDialog.cancel].type"
                 :title="cancel[orderStatusDialog.cancel].value"
      >
        <template v-if="orderStatusDialog.cancel === 1" #extra>
          <el-button type="success" @click="agreeCancelOrder">同意取消订单</el-button>
          <el-button type="danger" @click="rejectCancelOrder">驳回取消订单</el-button>
        </template>
      </el-result>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderStatusDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onActivated, onMounted, reactive, ref} from "vue";
import {Delete, Edit, Refresh} from "@element-plus/icons-vue";
import pagination from "@/components/pagination.vue";
/**
 * Order ——> 实体大驼峰
 * order ——> 实体小驼峰
 * 订单 ——> 实体中文名
 */
import {
  deleteOrderBatchByIds,
  getOrderPageList,
  okprintOrder,
  tonocancelOrder,
  tookMoney,
  toprintingOrder,
} from "@/apis/order";
import router from "@/router/index.js";
import {formatter} from "@/utils/utils.js";
import {useOrderDetailsStore} from "@/stores/order.js";
import {alipayReturn} from "@/apis/pay.js";

const orderDetailsStore = useOrderDetailsStore();

const status = [
  {key: 1, value: "创建订单", type: "info"},
  {key: 2, value: "申请报价", type: "info"},
  {key: 3, value: "报价完成", type: "success"},
  {key: 4, value: "完成支付", type: "success"},
  {key: 5, value: "正在打印 ", type: "info"},
  {key: 6, value: "打印完成", type: "success"},
  {key: 7, value: "订单完成", type: "success"}
]
const cancel = [
  {key: 0, value: "订单正在进行", type: "primary"},
  {key: 1, value: "申请取消订单", type: "warning"},
  {key: 2, value: "同意取消订单", type: "info"},
  {key: 3, value: "驳回取消订单", type: "danger"}
]

const QueryFormRef = ref();

const orderTableLoading = ref(false);
const selectionIds = ref([]);

const total = ref(0);

const params = reactive({
  page: 1,
  size: 10
});

const orderDataList = ref([]);

const orderStatusDialog = reactive({
  title: "修改订单状态",
  visible: false,
  id: "",
  status: "",
  cancel: "",
  quotation: "",
})

const mergeObj = ref({})
const mergeArr = reactive(['userId'])
//计算需要合并的数据
const getSpanArr = data => {
  mergeArr.forEach((key) => {
    let count = 0; // 用来记录需要合并行的起始位置
    mergeObj.value[key] = []; // 记录每一列的合并信息
    data.forEach((item, index) => {
      // index == 0表示数据为第一行，直接 push 一个 1
      if (index === 0) {
        mergeObj.value[key].push(1);
      } else {
        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
        if (item[key] === data[index - 1][key]) {
          mergeObj.value[key][count] += 1;
          mergeObj.value[key].push(0);
        } else {
          // 如果当前行和上一行其值不相等
          count = index; // 记录当前位置
          mergeObj.value[key].push(1); // 重新push 一个 1
        }
      }
    })
  })
}
//合并行方法
const objectSpanMethod = ({row, column, rowIndex, columnIndex}) => {
  // 判断列的属性
  if (mergeArr.indexOf(column.property) !== -1) {
    // 判断其值是不是为0
    if (mergeObj.value[column.property][rowIndex]) {
      return [mergeObj.value[column.property][rowIndex], 1]
    } else {
      // 如果为0则为需要合并的行
      return [0, 0];
    }
  }
}
/** 查询 */
const handleQuery = () => {
  orderTableLoading.value = true;
  getOrderPageList(params)
      .then(({data}) => {
        orderDataList.value = data.list;
        getSpanArr(data.list);
        total.value = data.totalCount;
        total.value = 448
      })
      .finally(() => {
        orderTableLoading.value = false;
      });
}

/** 重置查询 */
const resetQuery = () => {
  QueryFormRef.value.resetFields();
  handleQuery();
}

/** 行checkbox 选中事件 */
const handleSelectionChange = selection => {
  selectionIds.value = selection.map((item) => item.id);
}

/** 打开修改状态弹窗 */
const openOrderStatusDialog = row => {
  orderStatusDialog.visible = true;
  orderStatusDialog.id = row.id;
  orderStatusDialog.status = row.status;
  orderStatusDialog.cancel = row.cancel;
  orderStatusDialog.totalAmount = row.totalAmount;
  orderStatusDialog.tradeNo = row.tradeNo;
  console.log(orderStatusDialog)
}
const closeOrderStatusDialog = () => {
  orderStatusDialog.visible = false;
}
/** 处理订单状态步骤改变 */
const handleOrderStatusStep = step => {
  if (step > orderStatusDialog.status) {
    if (step === 3) {
      tookMoney(orderStatusDialog.id, orderStatusDialog.quotation).then(() => {
        ElMessage.success("报价成功")
        orderStatusDialog.status = step;
        handleQuery();
        closeOrderStatusDialog();
      })
    } else if (step === 5) {
      toprintingOrder(orderStatusDialog.id).then(() => {
        ElMessage.success("开始打印")
        orderStatusDialog.status = step;
        handleQuery();
        closeOrderStatusDialog();
      });
    } else if (step === 6) {
      okprintOrder(orderStatusDialog.id).then(() => {
        ElMessage.success("打印完成")
        orderStatusDialog.status = step;
        handleQuery();
        closeOrderStatusDialog();
      });
    }
  } else ElMessage.warning("不能回退");
}
/** 同意取消订单 */
const agreeCancelOrder = () => {
  alipayReturn(orderStatusDialog.id, orderStatusDialog.tradeNo, orderStatusDialog.totalAmount).then(() => {
    ElMessage.success("同意取消订单成功")
    handleQuery();
    closeOrderStatusDialog();
  })
}
/** 驳回取消订单 */
const rejectCancelOrder = () => {
  tonocancelOrder(orderStatusDialog.id).then(() => {
    ElMessage.success("驳回取消订单成功")
    handleQuery();
    closeOrderStatusDialog();
  })
}

/** 删除订单 */
const handleDelete = row => {
  ElMessageBox.confirm(`确认删除订单${row.id}?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    orderTableLoading.value = true;
    deleteOrderBatchByIds([row.id])
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (orderTableLoading.value = false));
  });
}
/** 批量删除 */
const handleBatchDelete = () => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    orderTableLoading.value = true;
    deleteOrderBatchByIds(selectionIds.value)
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (orderTableLoading.value = false));
  });
}

/** 展开行 */
const handleRowClick = row => {
  orderDetailsStore.addOrderDetailsById(row.id, row);
  const {href} = router.resolve({
    name: "details",
    params: {id: row.id}
  })
  window.open(href, "_blank")
}

/** 初始化 */
onMounted(() => {
  handleQuery();
});
onActivated(() => {
  handleQuery();
})
</script>
<style scoped>
:deep(.pagination) {
  display: flex;
  justify-content: center;
}

:deep(.el-step__icon) {
  cursor: pointer;
}

</style>
